package com.yjps.common.timer;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 如何散射和聚集读写结构化文件 NIO是非阻塞的 比较耗资源
 * Created by jessy on 2015/8/29.
 */
public class NIOScatteringandGathering {
    public void createFiles(String TPATH){
        try {
            //把byte数组包装成Buffer
            ByteBuffer bookBuf = ByteBuffer.wrap("java 性能优化技巧".getBytes("GBK"));
            ByteBuffer autBuf = ByteBuffer.wrap("test".getBytes("GBK"));
            /*在Buffer上进行的读写操作都不能越过这个下标。当写数据到buffer中时，limit一般和capacity相等，当读数据时，limit代表buffer中有效数据的长度。*/
            int booklen = bookBuf.limit();
            int autlen = autBuf.limit();
            ByteBuffer[] bufs = new ByteBuffer[]{bookBuf,autBuf};
            File file = new File(TPATH);
            if(!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                FileOutputStream fos = new FileOutputStream(file);
                FileChannel fc = fos.getChannel();
                fc.write(bufs);
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*创建一个指定capacity的ByteBuffer。*/
            ByteBuffer b1 = ByteBuffer.allocate(booklen);
            ByteBuffer b2 = ByteBuffer.allocate(autlen);
            ByteBuffer[] bufs1 = new ByteBuffer[]{b1,b2};
            File file1 = new File(TPATH);
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                /*Channel表现了一个可以进行IO操作的通道*/
            FileChannel fc = fis.getChannel();
                fc.read(bufs1);
                System.out.println("读取。。。。");
                String bookname = new String(bufs1[0].array(),"GBK");
                String autname = new String(bufs1[1].array(),"GBK");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        NIOScatteringandGathering nio = new NIOScatteringandGathering();
        nio.createFiles("C:\\1.TXT");
    }
}
